#include "rd522_lpcd.h"
#include "iso14443.h"

extern uint8_t uid_f;
uint8_t g_lpcdfirstTime = 0;

void lpcd_exreg_init(unsigned char calib_min, unsigned char calib_max, unsigned char fastdete, unsigned char clksel)	//0-外部晶振 1-内部RC
{
//		write_reg(analogen_reg, 0xf);
//		write_lpcd_exreg(0x16, 0xC);			//开启RC_OSC OSC_EN；
		write_lpcd_exreg(lpcd_t1_reg, 0x3); 	// (n+2) * 100ms
		write_lpcd_exreg(lpcd_t2_reg, 18);		// 默认 (n + 2) * 10us,
		write_lpcd_exreg(lpcd_t3_reg, 0x2);		//  
//		write_lpcd_exreg(lpcd_autowukup_reg,8);//开启定时唤醒
	
		write_lpcd_exreg(lpcd_thresholdhi_reg, calib_min);
		write_lpcd_exreg(lpcd_thresholdlo_reg, calib_max);
#if DEBUG
		printf("lpcd_thresholdhi_reg=%x\r\n", read_lpcd_exreg(lpcd_thresholdhi_reg));
		printf("lpcd_thresholdlo_reg=%x\r\n", read_lpcd_exreg(lpcd_thresholdlo_reg));
#endif	
		write_lpcd_exreg(fastdetect_reg, 0x6 | (fastdete & 0x01));	//不配置快速检测，
		write_lpcd_exreg(lpcd_cwctr_reg,0x4);						//配置自动寻卡时的功率
		write_lpcd_exreg(lpcd_ncwctr_reg,1);
		write_lpcd_exreg(lpcd_analogen_reg, 0x00);//tvddSel	vmidEn	aldoEn	sbias2	opapd（模拟配置）
		write_lpcd_exreg(lpcd_rxgain_reg, 0x1f); //增益配置
		write_lpcd_exreg(lpcd_txctr_reg, 0x1b);  //开启载波
		
		if(clksel)//时钟配置，建议使用外部时钟
			write_lpcd_exreg(clk_conf_reg, read_lpcd_exreg(clk_conf_reg) & 0xe);
		else
			write_lpcd_exreg(clk_conf_reg, (read_lpcd_exreg(clk_conf_reg) & 0xe) | 1);
		
		#if DEBUG
		printf("clk_conf_reg = %02x\r\n",read_lpcd_exreg(clk_conf_reg));
		#endif
}

void lpcd_reg_preconfig(void)
{
	rd522_set_rate(RATE_106,14);//提前配值通信速率和接收等待时间	
}
void lpcd_enter(void)
{
	write_reg(txcontrol_reg, 0x00);//进入前关闭天线载波
	write_lpcd_exreg(lpcd_ctr1_reg,0x01U);//进入LPCD低功耗自动检卡
}

//卡片进场处理
void lpcd_cardin_irqhandler(void)
{
		unsigned char threshold_value=0;
//		unsigned char status;
		

		threshold_value = read_lpcd_exreg(lpcd_value_reg);
		if(g_lpcdfirstTime)
		{
			uid_f = 1;
//			printf("Card in\r\n");
			printf("adc_value = %x\r\n", threshold_value);
			//重新进入LPCD
//			Delay_ms(10);  
//			lpcd_enter();	//使能LPCD
		}
		else	//校准完
		{
				g_lpcdfirstTime=1;
				printf("adc_value = %x\r\n", threshold_value);
				//LPCD配置
				lpcd_exreg_init(0,threshold_value+1,0,0);//阈值上下各放宽一组，减少误触发
				//进入LPCD
				lpcd_enter();
		}
}

//lpcd自动唤醒中断
void lpcd_auto_wakeup_irq_handler(void)
{
		printf("Auto wake up\r\n");
		lpcd_enter();  //进入LPCD    
}
